package com.xys.libzxing.zxing.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.Result;
import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.view.activity.BaseActivity;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;

import com.handpay.nocardpay.baselibrary.qualificationinfo.comm.CommonHelper;
import com.handpay.nocardpay.baselibrary.qualificationinfo.comm.OkQrCodeReader;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.xys.libzxing.zxing.camera.CameraManager;
import com.xys.libzxing.zxing.decode.DecodeThread;
import com.xys.libzxing.zxing.utils.BeepManager;
import com.xys.libzxing.zxing.utils.CaptureActivityHandler;
import com.xys.libzxing.zxing.utils.InactivityTimer;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

import me.yokeyword.fragmentation.SupportActivity;


/**
 * This activity opens the camera and does the actual scanning on a background
 * thread. It draws a viewfinder to help the user place the barcode correctly,
 * shows feedback as the image processing is happening, and then overlays the
 * results when a scan is successful.
 */
public final class CaptureActivity extends SupportActivity implements SurfaceHolder.Callback {

    private static final String TAG = CaptureActivity.class.getSimpleName();

    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private SurfaceView scanPreview = null;
    private RelativeLayout scanCropView,scanContainer;
    private Rect mCropRect = null;
    private boolean isHasSurface = false;
    private Toolbar mToolbar=null;
    public Handler getHandler() {
        return handler;
    }
    private Toolbar toolbar;
    public CameraManager getCameraManager() {
        return cameraManager;
    }

    private String paperFromQualificationFragmentFlag="paperFromQualificationFragmentFlag";

    public boolean paperFromQualificationFragment=false;
    private final static int CHOOSE_PHOTO=10;

    protected void initToolbar(Toolbar toolbar, String title,boolean leftBackIcon,View.OnClickListener leftListener) {
        TextView mTitle = (TextView) toolbar.findViewById(R.id.tv_title);
        TextView mRightView = (TextView) toolbar.findViewById(R.id.iv_right);
        if(paperFromQualificationFragment){
            mRightView.setText(R.string.hint_select_photo);
            mRightView.setVisibility(View.VISIBLE);
            mRightView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectQrCodePicture();
                }
            });
        }
        toolbar.setTitle("");
        mTitle.setText(title);
        if (leftBackIcon) {
            toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            toolbar.setNavigationOnClickListener(leftListener);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_capture);
        paperFromQualificationFragment=getIntent().getBooleanExtra(paperFromQualificationFragmentFlag,false);
        mToolbar = (Toolbar) this.findViewById(R.id.toolbar);
        initToolbar(mToolbar, getString(R.string.scanner_sharecode), true, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
        ImageView scanLine = (ImageView) findViewById(R.id.capture_scan_line);
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.9f);
        animation.setDuration(3000);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        scanLine.startAnimation(animation);
    }

    /**
     * 选择二维码图片
     */
    private void selectQrCodePicture(){
        File imageFile = new File(Environment.getExternalStorageDirectory(), "outputImage.jpg");
        try {
            if (imageFile.exists()) {
                imageFile.delete();
            }
            imageFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        //转换成Uri
        Uri imageUri = Uri.fromFile(imageFile);
        Intent intent = new Intent();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }else{
            intent.setAction(Intent.ACTION_PICK);
        }
        intent.setType("image/*");
        //设置输出位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //开始选择
        startActivityForResult(intent, CHOOSE_PHOTO);
    }
    @Override
    protected void onResume() {
        super.onResume();

        // CameraManager must be initialized here, not in onCreate(). This is
        // necessary because we don't
        // want to open the camera driver and measure the screen size if we're
        // going to show the help on
        // first launch. That led to bugs where the scanning rectangle was the
        // wrong size and partially
        // off screen.
        cameraManager = new CameraManager(getApplication());

        handler = null;

        if (isHasSurface) {
            // The activity was paused but not stopped, so the surface still
            // exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(scanPreview.getHolder());
        } else {
            // Install the callback and wait for surfaceCreated() to init the
            // camera.
            scanPreview.getHolder().addCallback(this);
        }

        inactivityTimer.onResume();
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */
    public void handleDecode(Result rawResult, Bundle bundle) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
        Intent resultIntent = new Intent();
        bundle.putInt("with", mCropRect.width());
        bundle.putInt("height", mCropRect.height());
        bundle.putString("result", rawResult.getText());
        resultIntent.putExtras(bundle);
        HPLog.d("tag-handleDecode", "close");
        this.setResult(RESULT_OK, resultIntent);
        CaptureActivity.this.finish();

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }

            initCrop();
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage("Camera error");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }

        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.show();
    }

    public Rect getCropRect() {
        return mCropRect;
    }

    /**
     * 初始化识别区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;
        /** 宽高*/
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);
        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();
        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();
        /** xml框框区域 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();
        int x = cropLeft * cameraWidth / containerWidth;
        int y = cropTop * cameraHeight / containerHeight;
        int width = cropWidth * cameraWidth / containerWidth;
        int height = cropHeight * cameraHeight / containerHeight;
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==CHOOSE_PHOTO){
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String qrCode= OkQrCodeReader.with().readQrCodeContent(this,uri);
                if(!TextUtils.isEmpty(qrCode)){
                    HPLog.i(HPLog.LFP_TAG,"readQrCodeContent::qrCode="+qrCode);
                    Intent resultIntent = new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putInt("with", mCropRect.width());
                    bundle.putInt("height", mCropRect.height());
                    bundle.putString("result", qrCode);
                    resultIntent.putExtras(bundle);
                    this.setResult(RESULT_OK, resultIntent);
                    CaptureActivity.this.finish();
                }else{
                    readQrCodeContentNull();
                }
            }
        }
    }
    //如果没有包含二维码继续扫描
    private void readQrCodeContentNull() {
        DialogUtils.showAlertDialog(this, this.getString(R.string.tip), getString(R.string.hint_no_qr_code), true, this.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
    }
}